'''
抄一遍书上关于线程抢票的源码

'''
import threading
from time import *
from datetime import datetime

# 这里用字典或者类会更好
# 一个全局的列表
tickets = [['2018-4-7 8:00', '北京', '沈阳', 3, 120],
           ['2018-4-7 12:00', '上海', '沈阳', 2, 130],
           ['2018-4-3 13:00', '北京', '沈阳', 10, 120],
           ['2018-4-5 14:00', '广州', '武汉', 0, 200]
           ]


def buy_ticket(name, nums, date1, start_station):
    i = 0
    sleep(1)
    for get_record in tickets:
        if get_record[0] == date1 and get_record[1] == start_station:
            if get_record[3] >= nums:
                tickets[i][3] = get_record[3] - nums
                print('%s购买%d张票成功' % (name, nums))
                return
            else:
                print('%s现存票数量不够，无法购买！' % (name))
                return -1
        i += 1
    print("%s今日无票，无法购买！"%(name))
    return -1

if __name__ == '__main__':
    print('开始时间：', datetime.now())
    #调用threading的Thread方法
    #线程传参数一定要用args
    #本来直接调threading.Thread(target=buy_ticket('李春江', 3, '2018-4-7 12:00', '上海'))
    #会报错，原因是start() => _bootstrap() => _bootstrap_inner() => run()
    t1 = threading.Thread(target=buy_ticket,args=('李春江', 3, '2018-4-7 12:00', '上海'))
    t2 = threading.Thread(target=buy_ticket,args=('和假名', 1, '2018-4-7 8:00', '北京'))
    t3 = threading.Thread(target=buy_ticket,args=('吴灏明', 2, '2018-4-5 14:00', '广州'))
    t1.start()
    t2.start()
    t3.start()
    t1.join()
    t2.join()
    t3.join()
    print('结束时间：', datetime.now())
    print('剩余票数为：\n')
    for gets in tickets:
        print(gets)
